package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"waimai/param"
	"waimai/service"
	"waimai/tool"
)

type MemberController struct {

}
func(mc *MemberController)Router(engine *gin.Engine){
	engine.GET("/api/sendcode",mc.sendSmsCode)
	engine.POST("/api/login_sms",mc.smsLogin)
	engine.GET("/api/captcha",mc.captcha)

	//postman测试使用
	engine.POST("/api/vertifycha",mc.vertifyCaptcha)

	//密码登录
	engine.POST("/api/login_pwd",mc.nameLogin)
}

// /api/sendcode?phone=18037235202
func(mc *MemberController) sendSmsCode(c *gin.Context){
	phone,exist:=c.GetQuery("phone")
	if !exist{
		tool.Failed(c,"参数解析失败")
		return
	}
	fmt.Println(phone)
	ms:=service.MemberServie{}
	issend:=ms.SendCode(phone)
	if !issend{
		tool.Failed(c,"发送失败")
		return
	}
	tool.Success(c,"发送失败")

}

//手机号+短信登陆
func(mc *MemberController) smsLogin(c *gin.Context){
    var smsLoginParam param.SmsLoginParam
	err:= tool.Decode(c.Request.Body,&smsLoginParam)
    if err!=nil{
		tool.Failed(c,"解析失败")
		return
	}
	us :=service.MemberServie{}
	member :=us.SmsLogin(smsLoginParam)
	if member==nil{
		tool.Failed(c,"登录失败")
		return
	}
	tool.Success(c,member)
}

func (mc *MemberController) captcha(c *gin.Context){
	//生成二维码并返回
	tool.GenerateCaptcha(c)
	tool.Failed(c,"解析失败")
}
func (mc *MemberController) nameLogin(c *gin.Context){
	//解析参数
	var loginParam param.LoginParam
	err:=tool.Decode(c.Request.Body,&loginParam)
	if err!=nil{
		tool.Failed(c,"参数解析失败")
		return
	}
	//验证验证码
	valudate:=tool.InitRedisStore().Verify(loginParam.Id,loginParam.Value,false)
	if !valudate{
		tool.Failed(c,"验证码错误")
		return
	}
	//登录
	ms:=service.MemberServie{}
	member:=ms.Login(loginParam.Name,loginParam.Password)
	if member.Id!=0{
		tool.Success(c,&member)
		return
	}
	tool.Failed(c,"登录失败")
}

//验证验证码
func(mc *MemberController)vertifyCaptcha(c *gin.Context){
	var captcha tool.CaptchaResult
	err:=tool.Decode(c.Request.Body,&captcha)
	if err!=nil{
		tool.Failed(c,"参数解析失败")
		return
	}
	result:=tool.InitRedisStore().Verify(captcha.Id,captcha.VertifyValue,false)
	if result{
		tool.Success(c,"验证成功")
	}else{
		tool.Failed(c,"验证失败")
	}
}